#include "Protocol.hpp"
#include "util.hpp"

volatile bool quit = false;

static void Usage(char *str)
{
    cerr << "Usage: "<< str <<" ServerIp ServerPort\n";
}
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string ServerIp = argv[1];
    uint16_t ServerPort = atoi(argv[2]);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "socket: " << strerror(errno) << endl;
        exit(2);
    }
    struct sockaddr_in ServerSock;
    bzero(&ServerSock, sizeof(ServerSock));
    ServerSock.sin_family = AF_INET;
    inet_aton(ServerIp.c_str(), &ServerSock.sin_addr);
    ServerSock.sin_port = htons(ServerPort);

    if (connect(sock, (sockaddr*)&ServerSock, sizeof(ServerSock)) != 0)
    {
        cerr << "connect: " << strerror(errno) << endl;
        exit(3);
    }
    string message;
    while (!quit)
    {
        message.clear();
        cout << "请输入表达式: ";
        getline(cin, message);
        if (strcasecmp("quit", message.c_str()) == 0)
        {
            quit = true;
            continue;
        }
        Request req;
        if (makeRequst(message, req) != true)
        {
            continue;
        }
        string package;
        req.serialize(package);
        encode(package, package.size());
        ssize_t s = write(sock, package.c_str(), package.size());
        if (s > 0)
        {
            char buff[BUFFER_SIZE];
            ssize_t r = read(sock, buff, BUFFER_SIZE - 1);
            if (r > 0)
            {
                buff[s] = '\0';
            }
            string echoPackage = buff;
            Response res;
            uint32_t len = 0;

            string tmp{decode(echoPackage, len)};
            if (len > 0)
            {
                res.deserialize(tmp);
                printf("[exitcode: %d]: %d\n", res._exitCode, res._result);
            }
        }
        else 
        {
            break;
        }
    }
    close(sock);
    return 0;
}